package com.example.gaojt.androiddemo.boostDemo.aa;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by gaojt on 7/27/17.
 */

public class ProcServiceFilter extends ProcBaseFilter {

    private static final int MAX_SCAN_SERVICE = 256;

    private List<ActivityManager.RunningServiceInfo> mServiceList = null;

    public ProcServiceFilter(Context ctx) {
        super(ctx);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
            mServiceList = am.getRunningServices(MAX_SCAN_SERVICE);
        }

    }

    @Override
    public boolean doFilter(ProcessModel.ProcessInfo processInfo) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return false;
        }
        if (processInfo.mPkgList == null || mServiceList == null || mServiceList.size() == 0) {
            return false;
        }

        ArrayList<String> checkList = new ArrayList<String>();
        for (String pkgName : processInfo.mPkgList) {
            if (IniManager.getFlexibleValue(mContext,pkgName) == IniManager.PROCESS_FLEXIBLE_WHITE_LIST) {
                checkList.add(pkgName);
            }
        }
        if (checkList.size() == 0) {
            return false;
        }

        int serviceCount = 0;
        for (ActivityManager.RunningServiceInfo serviceInfo : mServiceList) {
            for (String pkgName : checkList) {
                if (pkgName.equalsIgnoreCase(serviceInfo.service.getPackageName())) {
                    serviceCount++;
                    break;
                }
            }
        }

        if (serviceCount == 0
                && ProcessOOMHelper.getProcessOOM(processInfo.mPid) >= ProcessOOMHelper.CACHED_APP_MIN_ADJ) {
            processInfo.mCleanSuggest = ProcessModel.ProcessInfo.PROC_SUGGEST_CLEAN;
            processInfo.mCleanStrategy = ProcessModel.ProcessInfo.PROC_STRATEGY_KILL;
            ProcessModel.ProcessAdvInfo processAdvInfo = new ProcessModel.ProcessAdvInfo();
            processAdvInfo.mDescription = ProcessModel.ProcessAdvInfo.UNUESD_SERVICE;
            processAdvInfo.mStatus = 1;
            processInfo.mAdvanceInfo.add(processAdvInfo);
            return false;
        }

        return false;
    }

}
